import os
import httplib2
import urllib.request
import PyPDF2
import time


def merge_pdfs(paths, output):
    pdf_writer = PyPDF2.PdfFileWriter()

    for path in paths:
        pdf_reader = PyPDF2.PdfFileReader(path, strict=False)
        for page in range(pdf_reader.getNumPages()):
            pdf_writer.addPage(pdf_reader.getPage(page))
    with open(output, 'wb') as out:
        pdf_writer.write(out)


def downFile1(mytime):
    year = mytime.tm_year
    month = mytime.tm_mon
    day = mytime.tm_mday
    year = str(year)
    month = str('%02d' % month)
    day = str('%02d' % day)
    files = []
    for i in range(1, 9, 1):
        connection = httplib2.HTTPConnectionWithTimeout("paper.people.com.cn")
        path = 'rmrb/images/' + year + '-' + month + '/' + day + '/' + '01' + '/rmrb' + year + month + day + str(
            '%02d' % i) + '.pdf'
        connection.request("HEAD", path)
        response = connection.getresponse()
        if response.status == 400:
            name = 'rmrb' + year + month + day + str('%02d' % i) + '.pdf'
            url = r'http://paper.people.com.cn/rmrb/images/' + year + '-' + month + '/' + day + '/' + str(
                '%02d' % i) + '/' + name
            urllib.request.urlretrieve(url, name)
            files.append(name)
    targetfile = 'rmrb' + year + month + day + '.pdf'
    merge_pdfs(files, targetfile)
    for file in files:
        os.remove(file)


def downFile2(mytime):
    year = mytime.tm_year
    month = mytime.tm_mon
    day = mytime.tm_mday
    year = str(year)
    month = str('%02d' % month)
    day = str('%02d' % day)
    files = []
    for i in range(1, 9, 1):
        name = year + month + day + str('%02d' % i) + '_pdf' + '.pdf'
        url = r'http://www.81.cn/jfjbmap/content/1/' + year + '-' + month + '/' + day + '/' + str(
            '%02d' % i) + '/' + name
        urllib.request.urlretrieve(url, name)
        files.append(name)
    targetfile = 'jfjb' + year + month + day + '.pdf'
    merge_pdfs(files, targetfile)
    for file in files:
        os.remove(file)


if __name__ == "__main__":
    downFile1(time.localtime())
    downFile2(time.localtime())
